/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wanhai.itm.liveListModel;

import com.wanhai.ejb.dbhandler.DBHandlerLocal;
import com.wanhai.itm.wditm101.vo.Wditm101_ITM4001VO;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.AbstractListModel;
import org.zkoss.zul.ext.Sortable;
import org.zkoss.zul.ListModelList;

/**
 *
 * @author m2434
 */
public class LiveListModel<T> extends ListModelList implements Sortable{
    private DBHandlerLocal handler;
    private T cond;
    private int pageSize = 20;
    private int totalSize = 0;
    private String orderBy = "";
    private final String CACHE_KEY= this.toString()+"_cache";
    private List<T> pageResult;
    
    
//    private final static String CACHE_KEY= LiveListModel.class+"_cache";
     
    public LiveListModel(DBHandlerLocal handler, T cond){
//        ListModelList lml = new ListModelList();
//        System.out.println("CACHE_KEY = "+CACHE_KEY);
        this.handler = handler;
        this.cond = cond;
        this.setMultiple(true);
    }
     
    public T getElementAt(int index) {
        Map<Integer, T> cache = getCache();
 
        T targetVO = cache.get(index);
        
        if (targetVO == null){
            try{
                int page = (index / pageSize)+1;
                handler.setOrderBy(orderBy);
                pageResult = handler.partialQuery(cond,page,pageSize);
                super._list = pageResult;
                
                int indexKey = (index / pageSize) ;
                indexKey = indexKey * pageSize;
                
                for (T o : pageResult ){
                    cache.put(indexKey, o);
                    indexKey++;
                }
            }catch(Exception e){
                System.out.println("liveModel error"+ e);
            }
        }else{
            return targetVO;
        }

        targetVO = cache.get(index);
//        System.out.println("cache = "+cache);
//        System.out.println("index = "+index);
//        System.out.println("DAY_OF_WEEK = "+((ITM4001VO)targetVO).getDAY_OF_WEEK());
        if (targetVO == null){
            throw new RuntimeException("Element at index "+index+" cannot be found in the database.");
        }else{
            return targetVO;
        }
    }
     
    @Override
    public int indexOf(Object elem)
    {
//        System.out.println("elem = "+((Wditm101_ITM4001VO)elem).getDayOfWeekStr());
//        System.out.println("in indexof.size = "+super._list.size());
        System.out.println("_list.indexOf = "+super._list.indexOf(elem));
        return super._list.indexOf(elem);
    }
    
    private Map<Integer, T> getCache(){
        Execution execution = Executions.getCurrent();
        Map<Integer, T> cache = (Map)execution.getAttribute(CACHE_KEY);
        if (cache == null){
            cache = new HashMap<Integer, T>();
            execution.setAttribute(CACHE_KEY, cache);
        }
        return cache;
    }   
 
    public int getSize() {
        try{
            if(totalSize == 0){
                totalSize = handler.getQueryRecordCount(cond);
                System.out.println("LiveListModel sql = "+handler.getSQL());
            }
        }catch(Exception e){
            System.out.println("LiveListModel getSize error "+e);
        }
        
        return totalSize;
    }
    
    public void setOrderBy(String orderBy){
        this.orderBy = orderBy;
    }

    public List<T> getPageResult() {
        return pageResult;
    }

    public int getPageSize() {
        return pageSize;
    }
    
    @Override
    public void sort(Comparator cmpr, boolean ascending) {
        System.out.println("-------in sort--------"+this.orderBy);
//        String orderBy =((RowComparator)cmpr).getColumn().getLabel();
//        String orderBy = ((FieldComparator)cmpr).getRawOrderBy();
//        System.out.println("-------column--------"+orderBy);
//        System.out.println("-------cmpr--------"+cmpr.getClass().getName());
//        System.out.println("-------ascending--------"+ascending);
        
//        local.setOrderBy(orderBy + " " + (ascending?"asc":"desc"));
//        getElementAt(1);
//        fireEvent(ListDataEvent.CONTENTS_CHANGED, -1, -1);
    }
    
    @Override
    public String getSortDirection(Comparator cmpr) {
//        if (Objects.equals(_sorting, cmpr))
//            return _ascending ?  "ascending" : "descending";
        return null;   
    }
}
